#!/usr/bin/env node

// GPIO冲突解决脚本
const { exec } = require('child_process');
const { promisify } = require('util');
const execAsync = promisify(exec);

console.log("🔧 GPIO冲突解决脚本");

async function runCommand(command) {
  try {
    const result = await execAsync(command);
    return { success: true, stdout: result.stdout.trim(), stderr: result.stderr.trim() };
  } catch (error) {
    return { success: false, error: error.message, stdout: '', stderr: error.stderr || '' };
  }
}

async function checkAndFixGPIOConflict() {
  console.log("\n🔍 检查和解决GPIO冲突...");
  
  // 1. 检查pigpio进程
  console.log("1. 检查pigpio进程:");
  const pigpioCheck = await runCommand('ps aux | grep pigpiod | grep -v grep');
  let pigpiodPID = null;
  
  if (pigpioCheck.success && pigpioCheck.stdout) {
    console.log("   发现pigpio后台进程:");
    const lines = pigpioCheck.stdout.split('\n');
    lines.forEach(line => {
      console.log(`   ${line}`);
      // 提取PID
      const parts = line.trim().split(/\s+/);
      if (parts.length > 1) {
        pigpiodPID = parts[1];
      }
    });
  } else {
    console.log("   未发现pigpio后台进程");
  }
  
  // 2. 如果发现pigpio进程，询问是否停止
  if (pigpiodPID) {
    console.log(`\n⚠️  发现pigpio进程(PID: ${pigpiodPID})可能与WiringPi冲突`);
    
    const readline = require('readline');
    const rl = readline.createInterface({
      input: process.stdin,
      output: process.stdout
    });
    
    const answer = await new Promise(resolve => {
      rl.question('是否停止pigpiod进程以避免冲突? (y/N): ', resolve);
    });
    rl.close();
    
    if (answer.toLowerCase() === 'y') {
      console.log("   停止pigpiod进程...");
      const stopResult = await runCommand(`sudo kill ${pigpiodPID}`);
      if (stopResult.success) {
        console.log("   ✅ pigpiod进程已停止");
        // 等待进程完全停止
        await new Promise(resolve => setTimeout(resolve, 1000));
      } else {
        console.log(`   ❌ 停止进程失败: ${stopResult.error}`);
      }
    } else {
      console.log("   保持pigpiod进程运行");
    }
  }
  
  // 3. 测试GPIO操作
  console.log("\n3. 测试GPIO操作:");
  
  // 设置引脚为输出模式
  const modeResult = await runCommand('gpio -g mode 13 out');
  console.log(`   设置引脚13为输出模式: ${modeResult.success ? '成功' : '失败'}`);
  
  // 写入高电平
  const writeResult = await runCommand('gpio -g write 13 1');
  console.log(`   写入高电平到引脚13: ${writeResult.success ? '成功' : '失败'}`);
  
  // 读取状态
  const readResult = await runCommand('gpio -g read 13');
  console.log(`   读取引脚13状态: ${readResult.success ? readResult.stdout : '读取失败'}`);
  
  // 写入低电平
  const writeLowResult = await runCommand('gpio -g write 13 0');
  console.log(`   写入低电平到引脚13: ${writeLowResult.success ? '成功' : '失败'}`);
  
  // 读取最终状态
  const readFinalResult = await runCommand('gpio -g read 13');
  console.log(`   读取引脚13最终状态: ${readFinalResult.success ? readFinalResult.stdout : '读取失败'}`);
  
  // 4. 验证结果
  console.log("\n4. 验证结果:");
  if (readResult.success && readResult.stdout === '1') {
    console.log("   ✅ 写入高电平后读取结果正确");
  } else {
    console.log("   ❌ 写入高电平后读取结果不正确");
  }
  
  if (readFinalResult.success && readFinalResult.stdout === '0') {
    console.log("   ✅ 写入低电平后读取结果正确");
  } else {
    console.log("   ❌ 写入低电平后读取结果不正确");
  }
  
  // 5. 提供使用建议
  console.log("\n💡 使用建议:");
  console.log("1. 如果需要使用WiringPi控制GPIO，请确保停止pigpiod进程");
  console.log("2. 如果需要使用pigpio，请考虑修改项目代码以使用pigpio库");
  console.log("3. 避免同时使用WiringPi和pigpio控制相同的GPIO引脚");
  
  return {
    pigpioFound: !!pigpiodPID,
    writeHighSuccess: writeResult.success,
    readHighResult: readResult.success ? readResult.stdout : null,
    writeLowSuccess: writeLowResult.success,
    readLowResult: readFinalResult.success ? readFinalResult.stdout : null
  };
}

async function main() {
  console.log("🚀 开始GPIO冲突解决");
  
  const result = await checkAndFixGPIOConflict();
  
  console.log("\n📋 执行结果:");
  console.log(`  发现pigpio进程: ${result.pigpioFound ? '是' : '否'}`);
  console.log(`  写入高电平: ${result.writeHighSuccess ? '成功' : '失败'}`);
  console.log(`  读取高电平: ${result.readHighResult !== null ? result.readHighResult : '失败'}`);
  console.log(`  写入低电平: ${result.writeLowSuccess ? '成功' : '失败'}`);
  console.log(`  读取低电平: ${result.readLowResult !== null ? result.readLowResult : '失败'}`);
  
  if (result.readHighResult === '1' && result.readLowResult === '0') {
    console.log("\n🎉 GPIO操作正常，问题已解决！");
  } else {
    console.log("\n⚠️  GPIO操作仍有问题，请检查硬件连接");
  }
}

main();